package compare;

import java.util.ArrayList;
import java.util.Collections;  
import java.util.Comparator;  

class Student{
    String name;  
    int age;  

    Student(String name, int age) {
        this.name = name;  
        this.age = age;  
    }  

    @Override  
    public String toString() {  
        return name + " (" + age + ")";  
    }  
}  

public class ComparatorDemo {  
    public static void main(String[] args) {  
        ArrayList<Student> people = new ArrayList<>();
        people.add(new Student("Alice", 30));
        people.add(new Student("Bob", 25));
        people.add(new Student("Charlie", 35));

        // 按年龄排序  
        Collections.sort(people, new Comparator<Student>() {
            @Override  
            public int compare(Student p1, Student p2) {
                return p1.age-p2.age; // 按年龄升序排序
            }  
        });  

        System.out.println("按年龄排序: " + people);  

        // 按名字排序  
        Collections.sort(people, new Comparator<Student>() {
            @Override  
            public int compare(Student p1, Student p2) {
                return p1.name.compareTo(p2.name); // 按名字升序排序  
            }  
        });  

        System.out.println("按名字排序: " + people);  
    }  
}  